package cn.tedu.hotel.repository.impl;

import cn.tedu.hotel.pojo.vo.RoomListItemVO;
import cn.tedu.hotel.pojo.vo.RoomStandardVO;
import cn.tedu.hotel.repository.IRoomRedisRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 *  处理房间缓存数据的实现类
 */
@Slf4j
@Repository
public class RoomRedisRepositoryImpl implements IRoomRedisRepository {

    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    public RoomRedisRepositoryImpl(){
        log.debug("创建处理缓存的类：RoomRedisRepositoryImpl");
    }

    @Override
    public void put(RoomStandardVO room) {
        String key = getItemKey(room.getId());
        redisTemplate.opsForValue().set(key,room);

    }

    @Override
    public RoomStandardVO get(Long id) {
        //获取key的值
        String key = getItemKey(id);
        // 根据key在Redis中查找 房间数据是否存在
        Serializable serializable = redisTemplate.opsForValue().get(key);
        RoomStandardVO room = null;
        if (serializable != null){
            // 强制类型转换
            if (serializable instanceof RoomStandardVO){
                room = (RoomStandardVO) serializable;
            }
        }
        return room;
    }

    @Override
    public Boolean deleteItem(Long id) {
        return redisTemplate.delete(getItemKey(id));
    }

    @Override
    public Boolean deleteList() {
        return redisTemplate.delete(ROOM_LIST_KEY);
    }

    @Override
    public Long deleteAll(Collection<String> keys) {
        return redisTemplate.delete(keys);
    }

    @Override
    public void putList(List<RoomListItemVO> rooms) {
        for (RoomListItemVO room : rooms){
            redisTemplate.opsForList().rightPush(ROOM_LIST_KEY, room);
        }

    }

    @Override
    public List<RoomListItemVO> getList() {
        List<Serializable> list = redisTemplate.opsForList().range(ROOM_LIST_KEY,0,-1);
        List<RoomListItemVO> rooms = new ArrayList<>();
        for (Serializable serializable : list){
            rooms.add((RoomListItemVO) serializable);
        }
        return rooms;
    }

    @Override
    public Set<String> getAllKeys() {
        return redisTemplate.keys("room:*");
    }


    private String getItemKey(Long id) {
        return ROOM_ITEM_KEY_PREFIX + id;
    }
}
